package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.ArticleInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import com.example.demo.util.ConstVariable;

import lombok.SneakyThrows;
import org.apache.ibatis.annotations.ResultMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 而Spring Boot框架项目接口返回 JSON格式的数据比较简单：
 * 在 Controller 类中使用@RestController注解即可返回 JSON格式的数据。
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;// 属性注入


    // 新增操作（发表博客）
    @RequestMapping("/add")
    public Object add(HttpServletRequest request, String title, String content) {
        // todo 非空校验
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null) {
            return AjaxResult.fail(-1, "当前用户未登录，博客发表失败！");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        int uid = userInfo.getId(); // 标记当前博客是那个用户发布的
        int rcount = 1; // 表示当前博客的阅读量，初始值（新发表的博客阅读量）==1
        int state = 1; // state表示当前博客状态 1 ==>已发布， 2==》编辑中，保存草稿
        // 新增博客
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setTitle(title);
        articleInfo.setContent(content);
        articleInfo.setUid(uid);
        articleInfo.setRcount(rcount);
        articleInfo.setState(state);
        int result = articleService.add(articleInfo);
        if (result == 1) {
            return AjaxResult.success("博客发表成功！", 1);
        }
        else {
            return AjaxResult.fail(-1, "数据库插入失败，博客发表失败，请稍后再试！");
        }
    }



    // 查询指定用户id的所有博客
    @SneakyThrows
    @RequestMapping("/get_mylist")
    public Object getMyBlogList(Integer uid, HttpServletResponse response) {

        if (uid <= 0) {
            // response.sendRedirect("/lolgin.html"); // 当前用户未登录
            return AjaxResult.fail(401, "当前用户未登录");
        }
        return AjaxResult.success("查找成功",articleService.getMyBlogList(uid));
    }




    // 查看指定博客id的博客详情-->博客详情页，此id为blogId，形参名称要和前端传过来的参数一致
    @RequestMapping("/get_by_blog_id")
    public Object selectByBlogId(int id) {
        if (id <= 0) {
            return AjaxResult.fail(-1, "参数出错，无法找到指定博客的相关信息！");
        }
        ArticleInfo articleInfo = articleService.selectByBlogId(id);
        if (articleInfo == null) {
            return AjaxResult.fail(-1, "数据库查询出错");
        }
        return AjaxResult.success("查找博客详情成功", articleInfo);
    }








    // 获取总的博客列表_无分页功能
    @RequestMapping("/get_list")
    public List<ArticleInfo> getBlogList() {
        return articleService.getBlogList();
    }




    // 获取总的博客列表（实现分页功能）
    @RequestMapping("/get_list_by_page")
    public Object getListByPage(Integer pindex, Integer psize) {
        HashMap<String, Object> data = new HashMap<>();
        // 登录进去后，第一次初始化页面时候url = list.html，即pindex是空的，username等也是空的
        if (pindex == null || pindex < 1) {
            pindex = 1;
        }
        if (psize == null || psize <= 0) {
            psize = 2;
        }

        int offset = (pindex - 1) * psize;
        List<ArticleInfo> list = articleService.getListByPage(psize, offset);
        // getPageCount函数————》得到总的博客条数
        int totalCount = articleService.getPageCount();
        data.put("list", list);
        data.put("count", totalCount);
        return AjaxResult.success("分页功能的实现", data);

    }
    // 删除指定博客id的博客
    @SneakyThrows
    @RequestMapping("/del")
    public Object del(HttpServletRequest request, int id, HttpServletResponse response) {
        ArticleInfo articleInfo = articleService.selectByBlogId(id);
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null) {
            // response.sendRedirect("/login.html");
            return AjaxResult.fail(401, "当前用户未登录！");
        }
        // 这篇博客的作者（uid）和当前登录的用户id相同才有权限删除
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (articleInfo.getUid() != userInfo.getId()) {
//            response.sendRedirect("/blog_list.html");
            return AjaxResult.fail(-1, "你不是该篇博客的作者，你无权限进行删除操作");
        }
        if (id <= 0) {
            return AjaxResult.fail(-1, "找不到要删除的博客，删除失败");
        }
        int result = articleService.del(id);
        if (result <= 0) {
            return AjaxResult.fail(-1, "数据库删除操作失败！");
        }
        // 获取该篇博客的作者id

        Queue<Integer> queue = new LinkedList<>();
        ArrayList<Integer> list = new ArrayList<>();
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        return AjaxResult.success("删除博客成功！", result);
    }
    /**
     * 修改指定id的博客内容或标题
     */
    @RequestMapping("/update")
    public Object update(HttpServletRequest request, int id, String title, String content) {
        if (id <= 0) return AjaxResult.fail(-1, "你指定的博客id有误，稍后再试！");

        ArticleInfo articleInfo = articleService.selectByBlogId(id);
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null) {
            // response.sendRedirect("/login.html");
            return AjaxResult.fail(401, "当前用户未登录！");
        }
        // 这篇博客的作者（uid）和当前登录的用户id相同才有权限删除
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (articleInfo.getUid() != userInfo.getId()) {
//            response.sendRedirect("/blog_list.html");
            return AjaxResult.fail(-1, "你不是该篇博客的作者，你无权限进行修改操作");
        }
        else {
            int ret = articleService.update(id, title, content);
            if (ret <= 0) {
                return AjaxResult.fail(-1, "数据库更新操作失败！");
            }
            else {
                return AjaxResult.success("更新博客成功", ret);
            }
        }
    }

}
